from datetime import datetime

from django.http import JsonResponse

from .models import Banner, Notice, Welcome, Collection
from .serializer import BannerSerializer,NoticeSerializer,CollectionSerializer,CollectionSaveSerializer
def welcome(request):
    # 1 查出Order值最大行对象返回前端
    res = Welcome.objects.all().order_by('-order').first()
    img = 'http://192.168.200.31:8000/media/{0}'.format(str(res.img))
    #img = 'http://192.168.200.100/media/{0}'.format(str(res.img))
    print(img)
    return  JsonResponse({ 'code': 1, 'msg': '成功', 'result': img })


from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin
from rest_framework.response import Response

class BannerView(GenericViewSet,ListModelMixin):
    queryset = Banner.objects.filter(is_delete=False).order_by('order')[:3]
    serializer_class = BannerSerializer

    def list(self,request,*args,**kwargs):
        res = super().list(request,*args,**kwargs)
        notice = Notice.objects.all().order_by('-create_time').first()
        serializer = NoticeSerializer(instance=notice)
        return Response({'code': 1,'msg': '成功', 'banner': res.data, 'notice': serializer.data })

## 添加删除方法  删除地址和传递参数id： http://ip:8000/smart/collection/id/
from  rest_framework.mixins import  DestroyModelMixin,CreateModelMixin
class CollectionView(GenericViewSet,ListModelMixin,DestroyModelMixin,CreateModelMixin):
    # 查询当天之前的--> 没过滤当前用户
    queryset = Collection.objects.all().filter(create_time__gte=datetime.now().date())
    serializer_class = CollectionSerializer
    def get_serializer_class(self):
        if self.action == 'create':
            return CollectionSaveSerializer
        else:
            return CollectionSerializer

    def list(self, request, *args, **kwargs):
        res = super().list(request, *args, **kwargs)
        today_count = len(self.get_queryset()) # 获取记录总数
        return Response({'code': 1, 'msg': '成功', 'result': res.data, 'today_count': today_count})

    # 删除人脸
    def destroy(self, request, *args, **kwargs):
        from libs.baidu_ai import BaiduFace

        instance = self.get_object()

        # 百度AI中删除
        baidu = BaiduFace()
        res = baidu.delete(instance.name_pinyin, instance.face_token)
        print(res)
        self.perform_destroy(instance)
        return Response()


from .models import Area
from .serializer import AreaSerializer

class AreaView(GenericViewSet, ListModelMixin):
    queryset = Area.objects.all()
    serializer_class = AreaSerializer

## 统计按天采集人数统计情况
from django.db.models import Count
from django.db.models.functions import Trunc
from .models import Collection
from .serializer import StatisticsListSerializer

# class StatisticsView(GenericViewSet,ListModelMixin):
#     # 做个分组
#     queryset = Collection.objects.annotate(date=Trunc('create_time', 'day')).values('date').annotate(count=Count('id')).values('date', 'count')
#     serializer_class = StatisticsListSerializer

## 统计数据
class StatisticsView(GenericViewSet, ListModelMixin):
    # 做个分组
    queryset = Collection.objects.annotate(date=Trunc('create_time', 'day')).values('date').annotate(count=Count('id')).values('date', 'count')
    serializer_class = StatisticsListSerializer


## 读取人脸识别
from libs.baidu_ai import BaiduFace

class FaceView(GenericViewSet):
    def create(self, request, *args, **kwargs):

        # 1 取出前端传入的人脸照片
        avatar_object = request.data.get('avatar')
        if not avatar_object:
            return Response({'code': 103, 'msg': '请正常提交人脸'})

        # 2 使用百度人脸库 --> 搜索
        ai = BaiduFace()
        res = ai.search(avatar_object)
        print(res)
        if res.get('error_code') == 0:
            #3 查到了，取出userid --> 能匹配成功多个，咱们只取第一条
            user_id = res.get('result').get('user_list')[0].get('user_id')
            score = res.get('result').get('user_list')[0].get('score')
            #4 去匹配采集库，查出用户详情
            user = Collection.objects.filter(name_pinyin=user_id).first()
            return Response({'code': 100, 'msg': '匹配成功。', 'name': user.name, 'score': score})
        else:
            return Response({'code': 102, 'msg': '匹配人员不是我们社区人员，请注意。'})

## 百度语音识别
from libs.baidu_ai import BaiduVoice

class VoiceView(GenericViewSet):
    def create(self, request, *args, **kwargs):
        # 1 拿出前端传过来的录音
        voice_object = request.data.get('voice')

        # 2 调用百度识别
        ai = BaiduVoice()
        result = ai.speed(voice_object)

        print(result)

        if result.get('err_no') == 0:
            return Response({'code': 100, 'msg': '识别成功', 'result': result.get('result')})
        else:
            return Response({'code': 101, 'msg': '识别失败'})
